package cn.android666.flavors

import android.content.pm.PackageManager
import android.content.pm.Signature
import java.security.NoSuchAlgorithmException
import android.os.Bundle
import android.util.Base64
import android.util.Log
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import java.security.MessageDigest

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        // 显示签名信息
        val signatureInfoTextView = findViewById<TextView>(R.id.signatureInfo)
        signatureInfoTextView.text = getSignatureInfo()
    }

    private fun getSignatureInfo(): String {
        try {
            val packageInfo = packageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES)
            val signatures: Array<Signature>? = packageInfo.signatures
            if (signatures.isNullOrEmpty()) {
                return "未找到签名信息"
            }
            val signature = signatures[0]
            val signatureBytes = signature.toByteArray()

            val md5 = getFingerprint(signatureBytes, "MD5")
            val sha1 = getFingerprint(signatureBytes, "SHA1")

            return "应用包名: $packageName\n\nMD5指纹:\n$md5\n\nSHA1指纹:\n$sha1"
        } catch (e: Exception) {
            Log.e("MainActivity", "获取签名信息失败", e)
            return "获取签名信息失败: ${e.message}"
        }
    }

    private fun getFingerprint(signatureBytes: ByteArray, algorithm: String): String {
        return try {
            val messageDigest = MessageDigest.getInstance(algorithm)
            messageDigest.update(signatureBytes)
            val digest = messageDigest.digest()

            bytesToHex(digest).chunked(2).joinToString(":")
        } catch (e: NoSuchAlgorithmException) {
            Log.e("MainActivity", "算法不存在: $algorithm", e)
            "算法错误"
        }
    }

    private fun bytesToHex(bytes: ByteArray): String {
        val hexArray = "0123456789ABCDEF".toCharArray()
        val hexChars = CharArray(bytes.size * 2)
        for (i in bytes.indices) {
            val v = bytes[i].toInt() and 0xFF
            hexChars[i * 2] = hexArray[v ushr 4]
            hexChars[i * 2 + 1] = hexArray[v and 0x0F]
        }
        return String(hexChars)
    }
}